package org.study.quartz.quartzmanager.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.study.quartz.quartzmanager.service.SchedulerManagerService;
import org.study.quartz.quartzmanager.vo.ResponseResult;
import org.study.quartz.quartzmanager.vo.ScheduleTaskInfo;
import org.study.quartz.quartzmanager.vo.SchedulerInfo;

import java.util.List;

/***
 * 定时任务管控
 * @author lyf
 */
@RestController
@RequestMapping("/quartz/manager")
public class QuartzManagerController {


    @Autowired
    private SchedulerManagerService schedulerManagerService;


    /***
     * 获取计划中的任务列表
     * @return
     */
    @RequestMapping(value = "/getPlanJobList")
    public ResponseResult getPlanJobList() {
        return getJobList(false);
    }

    /***
     * 获取运行中的任务列表
     * @return
     */

    @RequestMapping(value = "/getRunningJobList")
    public ResponseResult getRunningJobList() {
        return getJobList(true);
    }

    /***
     * 暂停任务操作
     * @param triggerKey
     * @return
     */

    @RequestMapping(value = "/pause/{triggerKey}/task")
    public ResponseResult pauseTask(@PathVariable("triggerKey") String triggerKey) {

        return stopOrResumeSchedule(triggerKey, true);
    }

    /***
     * 恢复任务操作
     * @param triggerKey
     * @return
     */
    @RequestMapping(value = "/resume/{triggerKey}/task")
    public ResponseResult resumeTask(@PathVariable("triggerKey") String triggerKey) {
        return stopOrResumeSchedule(triggerKey, false);
    }


    /***
     * 停止整个任务信息
     * @return
     */

    @RequestMapping(value = "/pause")
    public ResponseResult pauseAll() {
        boolean success = this.schedulerManagerService.pauseAll();
        return doResult(success, success ? "success" : "failed");
    }

    /**
     * 恢复所有的任务信息
     *
     * @return
     */

    @RequestMapping(value = "/resume")
    public ResponseResult resumeAll() {
        boolean success = this.schedulerManagerService.resumeAll();
        return doResult(success, success ? "success" : "failed");
    }

    /**
     * 关闭任务
     *
     * @return
     */

    @RequestMapping(value = "/close/scheduler")
    public ResponseResult closeScheduler() {
        boolean success = this.schedulerManagerService.pauseScheduler();
        return doResult(success, success ? "success" : "failed");
    }

    /**
     * 启动任务信息
     *
     * @return
     */

    @RequestMapping(value = "/start/scheduler")
    public ResponseResult startScheduler() {
        boolean success = this.schedulerManagerService.startScheduler();
        return doResult(success, success ? "success" : "failed");
    }

    /***
     * 获取所有的任务信息
     * @return
     */

    @RequestMapping(value = "/list")
    public ResponseResult getAllTaskList() {
        ResponseResult result = new ResponseResult();
        SchedulerInfo schedulerInfo = schedulerManagerService.getAllTaskList();
        result.setCode(ResponseResult.SUCCESS);
        result.setData(schedulerInfo);
        return result;
    }


    /***
     * 添加任务信息 TODO
     * @return
     */
    @RequestMapping(value = "/add")
    public ResponseResult add() {
        ResponseResult result = new ResponseResult();

        String jobName = "taskMinuteJobDetail";
        String jobGroup = "DEFAULT";
        String jobBeanName = "taskMinuteJob";
        String executeMethod = "execute";
        String cronExpression = "0 */1 * * * ?";
        boolean success = schedulerManagerService.addJob(jobName, jobGroup, jobBeanName, executeMethod, cronExpression);
        result.setCode(success ? ResponseResult.SUCCESS : ResponseResult.ERROR);
        result.setData(success);

        return result;
    }


    /***
     * 删除任务操作
     * @return
     */
    @RequestMapping(value = "/{jobName}/{jobGroup}/delete")
    public ResponseResult delete(@PathVariable("jobName") String jobName, @PathVariable("jobGroup") String jobGroup) {
        ResponseResult result = new ResponseResult();
        boolean success = schedulerManagerService.deleteJob(jobName, jobGroup);
        result.setCode(success ? ResponseResult.SUCCESS : ResponseResult.ERROR);
        result.setData(success);
        return result;
    }

    /***
     * 立即对任务进行执行
     * @param jobName
     * @param jobGroup
     * @return
     */
    @RequestMapping(value = "/{jobName}/{jobGroup}/run")
    public ResponseResult runJobNow(@PathVariable("jobName") String jobName, @PathVariable("jobGroup") String jobGroup) {
        ResponseResult result = new ResponseResult();
        boolean success = schedulerManagerService.runJobNow(jobName, jobGroup);
        result.setCode(success?ResponseResult.SUCCESS:ResponseResult.ERROR);
        result.setData(success);
        return result;
    }


    /***
     * 显示结果信息
     * @param success
     * @param message
     * @return
     */
    private ResponseResult doResult(boolean success, String message) {
        ResponseResult result = new ResponseResult();
        if (success) {
            result.setCode(ResponseResult.SUCCESS);
        } else {
            result.setCode(ResponseResult.ERROR);
        }
        result.setMessage(message);
        return result;
    }

    /***
     * 停止或者恢复任务操作
     * @param triggerKey
     * @param stop
     * @return
     */
    private ResponseResult stopOrResumeSchedule(String triggerKey, boolean stop) {
        ResponseResult res = new ResponseResult();
        try {
            String[] keys = triggerKey.split("\\.");
            boolean operation = stop == false ? this.schedulerManagerService.resumeSchedule(keys[1], keys[0])
                    : this.schedulerManagerService.pauseSchedule(keys[1], keys[0]);
            if (operation) {
                res.setCode(ResponseResult.SUCCESS);
                res.setMessage("success");
            } else {
                res.setCode(ResponseResult.ERROR);
                res.setMessage("failed");
            }

        } catch (Exception e) {
            res.setCode(ResponseResult.ERROR);
            res.setMessage(e.getMessage());
        }

        return res;
    }

    /***
     * 获取任务列表信息,运行中的或者计划中的
     * @param running
     * @return
     */
    private ResponseResult getJobList(boolean running) {
        ResponseResult result = new ResponseResult();
        try {
            List<ScheduleTaskInfo> taskInfoList = running ? schedulerManagerService.getRunningScheduleList() : schedulerManagerService.getPlanedScheduleList();
            result.setCode(ResponseResult.SUCCESS);
            result.setMessage("query success");
            result.setData(taskInfoList);
        } catch (Exception e) {
            result.setCode(ResponseResult.ERROR);
            result.setMessage("query failed");
        }
        return result;
    }


}
